Popular Searches
Popular Course Categories
Popular Courses

Creating Cards, App Bars, and Floating Action Buttons

Creating Cards, App Bars, and Floating Action Buttons

Material Design and Advanced UI Components

Creating Cards, App Bars, and Floating Action Buttons in Android

Course: Android App Development

Topic: Creating Cards, App Bars, and Floating Action Buttons

Course Link: Android App Development Course

Demo Link: Register for a Free Course Demo

Website: JustAcademy


1. Introduction

Modern Android applications need user interfaces that are attractive, organized, consistent, and easy to navigate. Cards, app bars, and Floating Action Buttons (FABs) are important UI components that help developers build professional Android applications using Material Design principles.

Cards organize related information into individual containers. App bars provide screen titles, navigation controls, and important actions. Floating Action Buttons highlight the primary action that users can perform on a screen.

These components can be implemented using traditional Android Views with XML layouts and Material Components or using Jetpack Compose with Material 3 components.

2. Learning Objectives

  • Understand the purpose of cards, app bars, and Floating Action Buttons.
  • Create attractive cards using Material Design components.
  • Implement top app bars with titles, navigation icons, and action menus.
  • Add Floating Action Buttons to perform primary screen actions.
  • Handle click events and connect UI components to application logic.
  • Customize colors, shapes, elevation, spacing, and typography.
  • Build a simple screen that combines all three components.
  • Apply accessibility and responsive design best practices.

3. Understanding Cards in Android

3.1 What Is a Card?

A card is a container that groups related content and actions into a visually distinct section. Cards are useful when an application displays information such as products, user profiles, articles, courses, dashboard summaries, or notifications.

A card may contain text, images, icons, buttons, descriptions, and other UI elements.

3.2 Common Uses of Cards

  • E-commerce: Display product images, names, prices, and purchase buttons.
  • Education: Display course titles, instructors, descriptions, and enrollment actions.
  • Social applications: Show user posts, profile information, and reactions.
  • Dashboards: Present statistics, reports, and summarized data.
  • News applications: Display headlines, images, and article summaries.

3.3 Material Card Components

In traditional Android development, the Material Components library provides card components such as MaterialCardView. In Jetpack Compose, developers can use the Card composable from Material 3.

Component Purpose
MaterialCardView Creates a customizable card in an XML-based Android layout.
Card Creates a card using Jetpack Compose.
ElevatedCard Displays a card with elevation in Jetpack Compose Material 3.
OutlinedCard Displays a card with an outlined appearance in Jetpack Compose Material 3.
Filled Card Uses a filled surface treatment to distinguish a content group.

4. Creating a Card Using XML and Material Components

4.1 Add the Material Components Dependency

For an XML-based Android project, add the Material Components dependency to the app-level Gradle file. Use a compatible version for your project's Android Gradle Plugin and SDK configuration.

dependencies {
    implementation("com.google.android.material:material:<compatible-version>")
}

Replace <compatible-version> with the appropriate stable version for your project. Sync Gradle after adding the dependency.

4.2 Define a Card in XML

Create a layout file such as item_course.xml and add a MaterialCardView with a title, description, and button.

<com.google.android.material.card.MaterialCardView
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_margin="16dp"
    app:cardCornerRadius="16dp"
    app:cardElevation="4dp"
    app:strokeWidth="1dp"
    app:strokeColor="?attr/colorOutline">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:padding="16dp">

        <TextView
            android:id="@+id/courseTitle"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Android Development"
            android:textSize="20sp"
            android:textStyle="bold" />

        <TextView
            android:id="@+id/courseDescription"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="8dp"
            android:text="Learn to build modern Android apps."
            android:textSize="14sp" />

        <com.google.android.material.button.MaterialButton
            android:id="@+id/courseButton"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="12dp"
            android:text="Explore Course" />

    </LinearLayout>
</com.google.android.material.card.MaterialCardView>

4.3 Explanation of Card Attributes

Attribute Explanation
layout_width Controls the horizontal size of the card.
layout_height Controls the card's vertical size.
cardCornerRadius Sets the roundness of the card's corners.
cardElevation Controls the card's shadow depth.
strokeWidth Sets the width of the card outline.
strokeColor Sets the outline color.
padding Creates space between the card content and its edges.

4.4 Handle Card Button Clicks in Kotlin

After inflating the layout in an Activity, connect the button to an action.

val courseButton =
    findViewById<com.google.android.material.button.MaterialButton>(
        R.id.courseButton
    )

courseButton.setOnClickListener {
    Toast.makeText(
        this,
        "Course selected",
        Toast.LENGTH_SHORT
    ).show()
}

This example displays a short message when the user taps the button. In a real application, the click handler could open a course details screen or navigate to another destination.

5. Creating Cards Using Jetpack Compose

Jetpack Compose provides declarative components for building Android interfaces directly in Kotlin. The Card composable groups related UI elements together.

5.1 Basic Card Example

@Composable
fun CourseCard() {
    Card(
        modifier = Modifier
            .fillMaxWidth()
            .padding(16.dp),
        shape = RoundedCornerShape(16.dp),
        elevation = CardDefaults.cardElevation(
            defaultElevation = 4.dp
        )
    ) {
        Column(
            modifier = Modifier.padding(16.dp)
        ) {
            Text(
                text = "Android Development",
                style = MaterialTheme.typography.titleLarge
            )

            Spacer(modifier = Modifier.height(8.dp))

            Text(
                text = "Learn layouts, navigation, and app architecture."
            )

            Spacer(modifier = Modifier.height(12.dp))

            Button(onClick = {
                // Open course details
            }) {
                Text("Explore Course")
            }
        }
    }
}

5.2 Important Compose Elements

  • Card creates the card container.
  • Modifier.fillMaxWidth() allows the card to occupy the available width.
  • Modifier.padding() adds spacing around or inside the component.
  • RoundedCornerShape() defines rounded corners.
  • CardDefaults.cardElevation() controls elevation.
  • Column arranges content vertically.
  • Spacer adds a defined amount of space.
  • MaterialTheme.typography applies typography from the app's theme.

6. Understanding App Bars

6.1 What Is an App Bar?

An app bar is a prominent horizontal region that appears near the top of an application screen. It communicates the current screen's identity and provides navigation or action controls.

For example, a shopping application may display the screen title, a search icon, and a shopping cart action in its app bar.

6.2 Types of App Bars

Type Description Typical Use
Top App Bar Displays the screen title and common actions at the top. Most application screens.
Center-Aligned Top App Bar Places the title in the center. Screens with a simple navigation structure.
Small Top App Bar Uses a compact layout. Simple screens with a few actions.
Medium Top App Bar Provides additional space for the title and supporting layout. Screens with longer titles or richer hierarchy.
Large Top App Bar Uses a larger title area that can collapse during scrolling. Content-heavy screens.
Bottom App Bar Places actions and sometimes navigation near the bottom. Layouts that emphasize bottom-positioned actions.

6.3 Common App Bar Elements

  • Navigation icon: Usually a back arrow or navigation drawer icon.
  • Title: Identifies the current screen.
  • Action icons: Provide functions such as search, settings, or sharing.
  • Overflow menu: Contains additional actions that do not fit in the main toolbar.
  • Branding: May include a logo or app identity where appropriate.

7. Creating an App Bar Using XML

7.1 Add a Material Toolbar

In an XML-based application, a Material Toolbar can be used as the top app bar. Place it at the top of the screen and configure its title and appearance.

<com.google.android.material.appbar.MaterialToolbar
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/topAppBar"
    android:layout_width="match_parent"
    android:layout_height="?attr/actionBarSize"
    android:background="?attr/colorSurface"
    app:title="My Learning App"
    app:titleTextColor="?attr/colorOnSurface"
    app:navigationIcon="@drawable/ic_arrow_back"
    app:menu="@menu/top_app_bar_menu" />

Ensure that ic_arrow_back exists in the drawable resources and that top_app_bar_menu is a valid menu resource. Use a theme-compatible toolbar configuration.

7.2 Create an App Bar Menu

Create a menu resource at res/menu/top_app_bar_menu.xml.

<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <item
        android:id="@+id/action_search"
        android:title="Search"
        android:icon="@drawable/ic_search"
        app:showAsAction="ifRoom" />

    <item
        android:id="@+id/action_settings"
        android:title="Settings"
        app:showAsAction="never" />

</menu>

7.3 Handle App Bar Actions in Kotlin

val toolbar =
    findViewById<com.google.android.material.appbar.MaterialToolbar>(
        R.id.topAppBar
    )

toolbar.setNavigationOnClickListener {
    onBackPressedDispatcher.onBackPressed()
}

toolbar.setOnMenuItemClickListener { item ->
    when (item.itemId) {
        R.id.action_search -> {
            Toast.makeText(
                this,
                "Search selected",
                Toast.LENGTH_SHORT
            ).show()
            true
        }

        R.id.action_settings -> {
            Toast.makeText(
                this,
                "Settings selected",
                Toast.LENGTH_SHORT
            ).show()
            true
        }

        else -> false
    }
}

The navigation listener handles the back action. The menu listener checks the selected menu item's ID and performs the corresponding action. Replace the Toast messages with real application navigation or business logic when required.

8. Creating an App Bar Using Jetpack Compose

In Jetpack Compose Material 3, TopAppBar and its variants provide ready-made app bar components.

8.1 Small Top App Bar Example

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun LearningTopBar(
    onBackClick: () -> Unit,
    onSearchClick: () -> Unit
) {
    TopAppBar(
        title = {
            Text("My Learning App")
        },
        navigationIcon = {
            IconButton(onClick = onBackClick) {
                Icon(
                    imageVector = Icons.AutoMirrored.Filled.ArrowBack,
                    contentDescription = "Navigate back"
                )
            }
        },
        actions = {
            IconButton(onClick = onSearchClick) {
                Icon(
                    imageVector = Icons.Default.Search,
                    contentDescription = "Search"
                )
            }
        }
    )
}

Import the appropriate Material 3, Compose UI, and Material icons packages. Some app bar APIs may require an opt-in annotation depending on the Compose Material 3 version used by your project.

8.2 Understanding the Parameters

  • title displays the screen title.
  • navigationIcon defines the navigation control.
  • actions contains secondary or frequently used actions.
  • IconButton provides a clickable icon control.
  • contentDescription supplies an accessible description for an icon.

9. Understanding Floating Action Buttons (FABs)

9.1 What Is a Floating Action Button?

A Floating Action Button is a prominent button that represents the primary action on a screen. It is commonly displayed above the main content, often near the bottom-right corner.

For example, a notes application may use a plus icon to create a note, while an email application may use a compose icon to start a new message.

9.2 Common FAB Actions

  • Create a new item.
  • Compose a message or email.
  • Add a task or reminder.
  • Start a recording.
  • Create a new document.
  • Initiate a primary workflow.

9.3 Types of Floating Action Buttons

Type Description Example
Regular FAB A compact, prominent circular or rounded button. Add a note.
Small FAB A smaller version for layouts requiring less visual emphasis. Add a secondary item.
Large FAB A larger button used when more emphasis is appropriate. Start an important action.
Extended FAB Combines an icon with a text label. Compose, Create Project.

10. Creating a Floating Action Button Using XML

10.1 Define a FAB in XML

Add a FloatingActionButton to a suitable parent layout, such as CoordinatorLayout, to position it over the screen content.

<com.google.android.material.floatingactionbutton.FloatingActionButton
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/addFab"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="bottom|end"
    android:layout_margin="16dp"
    android:contentDescription="Add new item"
    app:srcCompat="@drawable/ic_add"
    app:backgroundTint="?attr/colorPrimary"
    app:tint="?attr/colorOnPrimary" />

The parent layout determines whether layout_gravity is supported. In a CoordinatorLayout, use appropriate layout parameters or an anchor when the FAB needs to coordinate with another component.

10.2 Handle FAB Clicks in Kotlin

val addFab =
    findViewById<com.google.android.material.floatingactionbutton.FloatingActionButton>(
        R.id.addFab
    )

addFab.setOnClickListener {
    Toast.makeText(
        this,
        "Create a new item",
        Toast.LENGTH_SHORT
    ).show()
}

In a real application, this listener might open a form, navigate to a creation screen, or display a dialog.

11. Creating a Floating Action Button Using Jetpack Compose

11.1 Basic FAB Example

@Composable
fun AddItemFab(
    onAddClick: () -> Unit
) {
    FloatingActionButton(
        onClick = onAddClick,
        containerColor = MaterialTheme.colorScheme.primary,
        contentColor = MaterialTheme.colorScheme.onPrimary
    ) {
        Icon(
            imageVector = Icons.Default.Add,
            contentDescription = "Add new item"
        )
    }
}

11.2 Extended FAB Example

@Composable
fun CreateNoteFab(
    onCreateClick: () -> Unit
) {
    ExtendedFloatingActionButton(
        onClick = onCreateClick,
        icon = {
            Icon(
                imageVector = Icons.Default.Add,
                contentDescription = null
            )
        },
        text = {
            Text("Create Note")
        }
    )
}

An extended FAB is useful when the primary action needs a visible text label. Use the appropriate Material icons dependency and imports in your project.

12. Combining Cards, App Bars, and FABs in One Screen

A well-designed screen can use all three components together. The app bar identifies the page, cards organize its content, and the FAB provides a clear primary action.

12.1 Example: Learning Dashboard

Imagine an Android learning application that displays a list of courses.

  • App bar: Displays the title "My Courses" and a search action.
  • Cards: Display individual course titles, progress, and a View Details button.
  • FAB: Allows users to add a new course.

12.2 Complete Compose Screen Example

The following example combines a top app bar, a course card, and a FAB using Material 3 components.

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun CourseDashboard() {
    var courseCount by remember { mutableIntStateOf(1) }

    Scaffold(
        topBar = {
            TopAppBar(
                title = {
                    Text("My Courses")
                },
                actions = {
                    IconButton(onClick = {
                        // Open search screen
                    }) {
                        Icon(
                            imageVector = Icons.Default.Search,
                            contentDescription = "Search courses"
                        )
                    }
                }
            )
        },
        floatingActionButton = {
            FloatingActionButton(
                onClick = {
                    courseCount++
                }
            ) {
                Icon(
                    imageVector = Icons.Default.Add,
                    contentDescription = "Add course"
                )
            }
        }
    ) { innerPadding ->
        Column(
            modifier = Modifier
                .fillMaxSize()
                .padding(innerPadding)
                .padding(16.dp)
        ) {
            repeat(courseCount) { index ->
                Card(
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(bottom = 12.dp),
                    shape = RoundedCornerShape(16.dp),
                    elevation = CardDefaults.cardElevation(
                        defaultElevation = 3.dp
                    )
                ) {
                    Column(
                        modifier = Modifier.padding(16.dp)
                    ) {
                        Text(
                            text = "Android Course ${index + 1}",
                            style = MaterialTheme.typography.titleMedium
                        )

                        Spacer(
                            modifier = Modifier.height(8.dp)
                        )

                        Text(
                            text = "Learn Android UI and app development."
                        )

                        Spacer(
                            modifier = Modifier.height(12.dp)
                        )

                        Button(onClick = {
                            // Open course details
                        }) {
                            Text("View Details")
                        }
                    }
                }
            }
        }
    }
}

12.3 How the Screen Works

  1. Scaffold provides a standard structure for the screen.
  2. TopAppBar displays the screen title and search action.
  3. Column arranges the course cards vertically.
  4. Card groups each course's information and action.
  5. FloatingActionButton displays the add action.
  6. remember and mutableIntStateOf maintain the course count during recomposition.
  7. Tapping the FAB increases the count, and Compose redraws the list with an additional card.

Note: This is a UI demonstration. In a production application, the add action should create a real course model and update a data source rather than merely increasing a counter.

13. Styling and Theming

13.1 Colors

Use theme-based colors so cards, app bars, and FABs remain visually consistent across the application. In Compose Material 3, use MaterialTheme.colorScheme rather than hardcoding colors throughout the interface.

13.2 Shape and Corner Radius

Cards often use rounded corners to communicate grouping and create a softer appearance. Select a consistent shape system instead of assigning unrelated corner radii to every component.

13.3 Elevation and Shadows

Elevation helps distinguish floating or raised components from their background. Use it carefully: excessive shadows can make an interface look cluttered. Some visual elevation effects vary depending on the theme and platform rendering.

13.4 Spacing and Alignment

  • Maintain consistent spacing between cards.
  • Provide enough internal padding for readable content.
  • Align app bar icons and titles consistently.
  • Keep the FAB clear of important content and navigation controls.
  • Use scrolling containers when card content exceeds the available screen height.

14. Accessibility Best Practices

  • Provide meaningful content descriptions for icon-only controls.
  • Use readable text sizes and sufficient color contrast.
  • Make interactive targets large enough to tap comfortably; approximately 48 × 48 dp is a common Android guideline.
  • Do not rely on color alone to communicate an action or status.
  • Give buttons and icons clear, action-oriented labels.
  • Ensure that text remains readable when users increase system font size.
  • Check that the FAB does not cover card content, important buttons, or navigation elements.
  • Use accessibility testing tools and test with TalkBack where appropriate.

15. Common Mistakes and Troubleshooting

Problem Possible Cause Solution
MaterialCardView cannot be resolved Missing dependency or incorrect imports. Add the Material Components dependency and sync Gradle.
Icons are not displayed Missing drawable resources or incorrect icon imports. Verify the drawable resource or add the appropriate Compose icons dependency.
FAB overlaps content Incorrect parent layout or insufficient content padding. Use Scaffold or CoordinatorLayout appropriately and account for insets.
App bar actions do not respond Click listeners are not configured correctly. Verify menu item IDs and listener handling.
Cards appear too crowded Insufficient padding or too many elements. Improve spacing and prioritize important information.
Colors look incorrect in dark mode Hardcoded colors or incompatible theme settings. Use theme-aware colors and test light and dark themes.
Compose screen content is hidden Scaffold padding is not applied. Apply the provided inner padding to the content container.
FAB does not trigger an action Missing or incorrect onClick callback. Connect the callback to the intended operation.

16. Best Practices for Professional Android UI Design

  • Use cards only when content benefits from clear grouping; avoid wrapping every text element in a separate card.
  • Keep app bar actions limited to the most useful and frequently used operations.
  • Use a FAB for the screen's primary action, not for unrelated secondary actions.
  • Use consistent typography, color schemes, shapes, and spacing.
  • Prefer Material 3 components when building a new interface that follows Material 3 guidelines.
  • Keep UI logic manageable by separating reusable composables or XML layouts from application business logic.
  • Use ViewModels and observable UI state for data-driven screens.
  • Test different screen sizes, orientations, themes, and accessibility settings.
  • Use LazyColumn for large or dynamic lists of cards in Jetpack Compose.
  • Handle navigation and data persistence separately from simple UI click demonstrations.

17. Practical Exercises

Exercise 1: Create a Profile Card

  • Create a card that displays a profile image, name, and short biography.
  • Add a button labeled "View Profile".
  • Customize the card's corner radius, spacing, and elevation.

Exercise 2: Build a Custom App Bar

  • Create an app bar with a screen title and back navigation icon.
  • Add a search action and a settings menu item.
  • Display a suitable response when each action is selected.

Exercise 3: Implement a FAB

  • Add a FAB to a notes screen.
  • Use an add icon with a meaningful content description.
  • Open a dialog or creation screen when the user taps the FAB.

Exercise 4: Build a Course Dashboard

  • Display at least three course cards.
  • Include a top app bar with the title "My Learning".
  • Add a FAB for creating a new course.
  • Make the course list scrollable.
  • Test the screen in light mode and dark mode.

18. Mini Project: Course Management Screen

Project Objective: Create a simple course management screen that demonstrates the use of cards, an app bar, and a Floating Action Button.

Project Requirements

  1. Create a screen titled "Course Manager".
  2. Display each course in a separate card.
  3. Include a course title, description, and details button.
  4. Add a search icon to the app bar.
  5. Add a FAB that opens a form for entering a new course.
  6. Validate the course name before adding a course.
  7. Show a useful message when the course list is empty.
  8. Maintain consistent styling and accessible labels.

Expected Outcome

The final screen should provide a clear title, organized course information, and an obvious way to create a new course. This exercise can later be extended with a ViewModel, a repository, and a database such as Room.

19. Interview Questions and Answers

Q1. What is a Card in Android?

A card is a UI container that groups related information and actions in a visually distinct section. MaterialCardView is commonly used with XML layouts, while Card is available in Jetpack Compose.

Q2. What is the purpose of an app bar?

An app bar identifies the current screen and provides navigation controls, titles, and frequently used actions.

Q3. What is a Floating Action Button?

A FAB is a prominent button that highlights the primary action available on a screen, such as adding a note or creating a new item.

Q4. What is the difference between MaterialCardView and Compose Card?

MaterialCardView is a traditional Android View component used in XML-based interfaces. Compose Card is a declarative composable used in Jetpack Compose.

Q5. What is the difference between a regular FAB and an Extended FAB?

A regular FAB typically emphasizes an icon, while an Extended FAB combines an icon with a text label to communicate the action more explicitly.

Q6. How do you handle a FAB click in Kotlin?

For a View-based FAB, use setOnClickListener. For a Compose FAB, provide an action through its onClick parameter.

Q7. Why should theme colors be used?

Theme colors help maintain consistency and support different theme configurations, including light and dark appearances.

Q8. What is Scaffold in Jetpack Compose?

Scaffold provides a standard layout structure for components such as a top app bar, bottom bar, FAB, and main content.

Q9. How can a card list be made scrollable?

In XML, use an appropriate scrolling container or RecyclerView for larger data sets. In Compose, use LazyColumn for efficient rendering of lists.

Q10. How do you improve accessibility for icon buttons?

Provide meaningful content descriptions, maintain sufficient contrast, ensure comfortable touch targets, and test the interface with accessibility tools.

20. Quick Revision Checklist

  • Understand the purpose and types of Material cards.
  • Know how to configure card shape, elevation, outline, and padding.
  • Understand top app bars, navigation icons, and action menus.
  • Know how to handle toolbar menu clicks.
  • Understand regular, small, large, and extended FABs.
  • Know how to implement click handlers in XML-based Views and Compose.
  • Understand how Scaffold organizes a Compose screen.
  • Use theme-aware colors and consistent spacing.
  • Apply accessibility descriptions and touch-target guidelines.
  • Test the completed screen in different themes and screen sizes.

21. Conclusion

Cards, app bars, and Floating Action Buttons are fundamental components for creating modern Android interfaces. Cards organize content, app bars provide navigation and contextual actions, and FABs highlight the main action users can perform.

By combining these components with Material Design principles, consistent themes, accessible controls, and well-structured application logic, developers can create interfaces that are attractive, responsive, and easy to use. Practice implementing these patterns in both XML-based layouts and Jetpack Compose to develop stronger Android UI design skills.


Additional Learning Resources

Explore the Android App Development course and related learning opportunities through the links below.

Previous Next
whatsapp